/* eslint-disable */
console.log("tax injected");
import { transformDataByOpenWeb } from "./../../lib/openWebTransform.js";
import { getBase64 } from "./../../lib/utils.js";
import {
  pagesCwbb,
  cwbbOption,
  zzsOption,
  fjsfOption,
  zzsXqyOption,
  zeroQysds,
  zeroReportStart
} from "./zeroReport.js";
import YZ from "../commonModule/YZ.js";
let baseInfo;
let isOnLoad = false;

// 如果不执行onload
setTimeout(() => {
  // 发送获得零申报数据事件
  if (!isOnLoad) {
    window.onload();
  }
}, 5000);

window.onload = function () {
  isOnLoad = true;
  let urls = [
    "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/index.html",
    "http://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/index.html",
    "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wdxx/inex.html",
    "http://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wdxx/inex.html",
    "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wybs/index.html",
    "http://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wybs/index.html",
  ];
  window.postMessage(
    {
      event: "getZeroInfo",
    },
    "*"
  );

  // 登录填写账号密码
  if (/\/zjgfdzswj\/main\/index.html/g.test(window.location.pathname)) {
    window.postMessage(
      {
        event: "getBaseInfo",
      },
      "*"
    );
  }
  // 纳税申报表页面
  if (/\/nssb\/sb_nssb.html/g.test(window.location.pathname)) {
    $("#sbxm_zcsb_menu").on("click", "tbody tr", function () {
      let $tr = $(this),
        $td = $tr.find("td");
      let timeStart = $td.eq(1).text(),
        timeEnd = $td.eq(2).text();
      let typeTaxStr = $td.eq(0).text();

      let taxType = getTaxType(typeTaxStr);

      // 获取申报周期，填充数据
      let timeStr = timeStart + "~" + timeEnd;
      let period = getReportingCycle(timeStr);

      // 渲染填报时间，填报周期
      sendFilter(period, taxType);
    });
  }

  // 小企业现金流量表
  if (/cwbb_xqy_xjllb/g.test(window.location.pathname)) {
    sendFilter({}, "cash");
    return;
  }
  // 小企业资产负债表
  if (/cwbb_xqy_zcfzb/g.test(window.location.pathname)) {
    sendFilter({}, "balance");
    return;
  }
  // 小企业利润表
  if (/cwbb_xqy_lrb/g.test(window.location.pathname)) {
    sendFilter({}, "profit");
  }

  // 按期应申报界面
  if (
    /\/zjgfzjdzswjsbweb\/pages\/sb\/nssb\/sb_nssb.html/g.test(
      window.location.href
    )
  ) {
    $("#zcsb").click();
    setTimeout(function () {
      YZ.captureDataFromPage();
    }, 1000);
  }
};

function autoDeleteBox(data) {
  setTimeout(() => {
    let coloseBtn = $("body > div.zj-big-bg > div.zj-alert > div.zj-alert-header > span");
    if(coloseBtn.length) {
      coloseBtn[0].click();
      $('.zj-big-bg').css('display', 'none');
      setTimeout(() => {
        coloseBtn[0].click();
        $('.zj-big-bg').css('display', 'none');
      }, 3000);
    };
    let elem = document.querySelector("#yhxxpanel");
    if (elem && !elem.className.includes("hidden")) {
      let huaDong = document.querySelector(
        "#yhxxpanel > div.panelbody > div.panelcontent > div.para"
      );
      huaDong.scrollTop = huaDong.scrollHeight;
      document.querySelector("#yhxyagree").checked = true;
      document.querySelector("#readedyhxy").click();
    } else {
      // 自动登录
      autoInputAccount({ companyInfo: data.data.currentZeroInfo });
    }
  }, 1000);
}

window.addEventListener(
  "message",
  async function ({ data }) {
    // 只监听来自于content script的信息
    if (data.sender !== "content-script") {
      return false;
    }
    if (data.event === "setSaasData") {
      data = data.data;
      let sheet = data.saasData.sheet;
      if (sheet == "sds" || sheet == "zzs") {
        fillInput(data, sheet);
      } else {
        fillInput(await transformDataByOpenWeb(data));
      }
    }
    if (data.event === "getNationData") {
      getNationData();
    }

    if (data.event === "getBaseInfo") {
      baseInfo = data.data;
      autoInputAccount(baseInfo);
    }
    // 同步申报表种类
    if (data.event === "syncReportInfo") {
      YZ.startGetReportInfo();
    }
    // 同步申报表
    if (data.event === "syncReport") {
      YZ.startGetReport();
    }
    if (data.event === 'getYzmapiBack') {
      console.log(data.data);
      if(data.data.success) {
        let yzm = data.data.data.data.yzm;
        document.querySelector("#yhmcode").value = yzm.slice(0, 4);
        if(yzm && yzm.length > 0) {
          setTimeout(() => {
            document.querySelector("#yhmlogin").click();
          }, 1000);
        }
      }
    }

    // 获得零申报数据
    if (data.event === "getZeroInfoBack") {
      if (data.data.isOpenZeroReport) {
        let urls = [
          "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wdxx/index.html",
          "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wybs/index.html",
        ];
        // 自动关闭页面
        if (
          window.location.href.includes(
            "dzswjsbwebxyw/pages/sb/baseYwtx/sbb_tx/sb_"
          )
        ) {
          window.close();
        }
        // 开始零申报申报
        if (window.location.href.includes("https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/index.html")) {
          // 删除提示框
          autoDeleteBox(data);
        } else {
          await zeroReportStart(data.data);
        }
      }
    }

    // 明细表同步开始
    if (data.event === "asyncTableDetailStart") {
      console.log(12333);
    }

    // 明细表同步返回
    if (data.event === "asyncTableDetailRequestEnd") {
      console.log(data.data);
    }
  },
  false
);
/**
 * 获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: "2013", // 国税对应制度 2007 | 2013
    nsrsbh: "", // 纳税人申报号
    nsrmc: "", // 纳税人名称（纳税公司）
    skssqq: "", // 税款所属期起
    skssqz: "", // 税款所属期止
  };
  window.postMessage(
    {
      event: "backNationData",
      data: {
        taxInfo: taxInfo,
      },
    },
    "*"
  );
}

let isYzm = true;
function autoInputAccount({ companyInfo }) {
  // if (!companyInfo) return false;
  $("#loginopen").click();
  companyInfo = companyInfo || {};
  $("#username").val(
    companyInfo.nationalTaxAccount ||
      companyInfo.nationalTaxId ||
      companyInfo.nationalTaxNo
  );
  $("#password").val(companyInfo.nationalTaxPass);
  if(isYzm) {
    isYzm = false;
    getYzm();
  }
}

function fillInput({ saasData }) {
  let sheet = saasData.sheet;

  let message = "填报成功";
  try {
    let inputData = saasData.data;
    if (sheet == "sds" || sheet == "zzs") {
      inputData = delSdsData(inputData.openParams.inputData.data.profit);
    }
    console.log(saasData);
    // 年报特殊处理
    if (saasData.isYearReport) {
      inputData = YZ.hackYearReportInput(
        inputData,
        saasData.lastYearData,
        saasData.sheet
      );
    }
    for (let key in inputData) {
      let value = Number.parseFloat(inputData[key]).toFixed(2) || "0.00";
      if ($(`input#${key}`).length != 0 || $(`[name=${key}]`).length != 0) {
        if ($(`input#${key}`).length != 0) {
          if (saasData.isYearReport) {
            $(`input#${key}`).val(value);
          } else {
            $(`input#${key}`).val(value).trigger("blur");
          }
        } else if (saasData.isYearReport) {
          $(`input#${key}`).val(value);
        } else {
          $(`input#${key}`).val(value).trigger("blur");
        }
      }
    }
  } catch (e) {
    message = "填报失败" + e;
  }

  // todo finally
  window.postMessage(
    {
      event: "fillInputDone",
      data: {
        message: message,
      },
    },
    "*"
  );
}

function delSdsData(tableData) {
  let sdsData = {};
  // let gsInstitution = getGsInstitution();
  sdsData.yysr = tableData.BNLJJE_1;
  sdsData.yycb = tableData.BNLJJE_2;
  sdsData.lrze = tableData.BNLJJE_30;
  return sdsData;
}

function getTaxType(taxTypeStr) {
  let taxType = "balance";
  if (taxTypeStr.search("增值税") != -1) {
    taxType = "zzs";
  } else if (taxTypeStr.search("所得税") != -1) {
    taxType = "sds";
  } else if (taxTypeStr.search("财务报表") != -1) {
    taxType = "balance";
  }
  return taxType;
}

/**
 * @param timeStr 时间字符串 2017-04-01~2017-06-30
 * 获取申报周期并且填充数据
 */
function getReportingCycle(timeStr) {
  timeStr = timeStr || "~";
  timeStr = timeStr.split("~");
  let sssq_q = timeStr[0].substr(0, 7);
  let sssq_z = timeStr[1].substr(0, 7);

  return {
    sssq_q: sssq_q,
    sssq_z: sssq_z,
  };
}

function sendFilter(period, taxType) {
  let sssq_q = period.sssq_q,
    sssq_z = period.sssq_z;

  if (sssq_q && sssq_z) {
    window.postMessage(
      {
        event: "setPeriodAndType",
        data: {
          type: taxType,
          startTime: sssq_q,
          endTime: sssq_z,
        },
      },
      "*"
    );
  } else if (taxType) {
    window.postMessage(
      {
        event: "setPeriodAndType",
        data: {
          type: taxType,
        },
      },
      "*"
    );
  }
}

function getYzm () {
  setTimeout(async () => {
    let img = document.querySelector("#yhmimg");
    if (img && img.src) {
      let canvas = document.getElementById('canvasYzm');
      if(!canvas) {
        canvas = document.createElement('canvas');
        canvas.id = 'canvasYzm'
        canvas.width = img.width ;
        canvas.height = img.height ;  
      }
      let ctx = canvas.getContext('2d');
      ctx.clearRect(0,0,img.width ,img.height );
      ctx.drawImage(img, 0, 0, img.width , img.height );
      // var imageData = ctx.getImageData(0, 0, canvas.width , canvas.height );
      // var imageData_length = imageData.data.length / 4;
      // for (var i = 0; i < imageData_length; i++) {
      //   var red = imageData.data[i * 4];
      //   var green = imageData.data[i * 4 + 1];
      //   var blue = imageData.data[i * 4 + 2];
      //   var gray = 0.3 * red + 0.59 * green + 0.11 * blue;
      //   var new_black;
      //   if (gray > 180) {
      //       new_black = 255;
      //       // imageData.data[i * 4] = new_black;
      //       // imageData.data[i * 4 + 1] = new_black;
      //       // imageData.data[i * 4 + 2] = new_black;
      //   } else {
      //       new_black = 0;
      //       imageData.data[i * 4] = 255;
      //       imageData.data[i * 4 + 1] = 0;
      //       imageData.data[i * 4 + 2] = 0;
      //   }
      // }
      // ctx.putImageData(imageData, 0, 0);
      // document.querySelector("#yhmwrapper").appendChild(canvas);
      let imgSrc = img.src.split('?')[0];
      let ext = imgSrc.substring(imgSrc.lastIndexOf('.') + 1).toLowerCase();
      let dataUrl = canvas.toDataURL('images/' + ext);
      // console.log(dataUrl);
      // let dataUrl = '';
      // console.log(dataUrl);
      // let base64Image = await getBase64(img.src);
      window.postMessage(
        {
          event: "getYzmapi",
          data: {
            base64Image: dataUrl.split(',')[1],
            keyWord: '01',
            type: '1'
          },
        },
        "*"
      );
    }
  }, 3000);  
}


